//
//  MyStoreObserver.m
//  SignatureN
//
//  Created by fanshao on 09-9-1.
//  Copyright 2009 Sensky. All rights reserved.
//

#import "MyStoreObserver.h"
#import<UIKit/UIKit.h>
#import<UIKit/UIAlert.h>
#import "HubuAppDelegate.h"
#import "HubuViewController.h"

@implementation MyStoreObserver

- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions
{
	//NSLog(@"paymetnQueue");
	for (SKPaymentTransaction* transaction in transactions)
	{
		switch (transaction.transactionState)
		{
			case SKPaymentTransactionStatePurchased:
				NSLog(@"Complete Transaction");
				[self completeTransaction:transaction];
				break;
			case SKPaymentTransactionStateFailed:
				NSLog(@"Failed Transaction");
				[self failedTransaction:transaction];
				break;
			case SKPaymentTransactionStateRestored:
				NSLog(@"Restored Transaction");
				[self restoreTransaction:transaction];
				break;
			default:
				break;
		}
	}
}

- (void)restoreClick {
    [[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
}

- (void) completeTransaction: (SKPaymentTransaction *)transaction {
	//NSLog(@"Transaction　complete");
	//NSString *response = [GTMBase64 stringByEncodingData:[transaction transactionReceipt]];
    /*
	NSString *response = [[[NSString alloc] initWithData:[transaction transactionReceipt] encoding:NSUTF8StringEncoding] autorelease];
	response = [response stringByReplacingOccurrencesOfString:@"+" withString:@"%2B"];
	NSLog(response);
     */
	NSString *productid = [[transaction payment] productIdentifier];
	//NSLog(@"购买完成的产品iD=%@",productid);
	HubuAppDelegate *delegate = (HubuAppDelegate *)[[UIApplication sharedApplication] delegate];
    
    UIButton *currentDownloadButton = (UIButton *)[delegate.hubuViewController.view viewWithTag:delegate.hubuViewController.downloadButtonTag];
    if(currentDownloadButton != nil) {
        delegate.hubuViewController.isDownloading = TRUE;
        [currentDownloadButton setTitle:@"下载中" forState:UIControlStateNormal];
        [currentDownloadButton removeTarget:self action:@selector(buyButtonClick:) forControlEvents:UIControlStateNormal];
        [currentDownloadButton setEnabled:NO];
    }
	//[delegate downloadWork:productid recepitdata:response];
    //[delegate.viewController downBook:productid];
    [delegate.hubuViewController downloadStartNow];
	[[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}

- (void) failedTransaction: (SKPaymentTransaction *)transaction
{
	NSLog(@"transaction failed");
	if (transaction.error.code != SKErrorPaymentCancelled)
    {
		UIAlertView *alerView =  [[UIAlertView alloc] initWithTitle:@"警告" message:[transaction.error localizedDescription]
								delegate:nil cancelButtonTitle:@"关闭" otherButtonTitles:nil];
		
		[alerView show];
		[alerView release];
    }
	
	[[SKPaymentQueue defaultQueue] finishTransaction: transaction];
    
    HubuAppDelegate *delegate = (HubuAppDelegate *)[[UIApplication sharedApplication] delegate];
	delegate.hubuViewController.isDownloading = FALSE;
//	ArtdepotAppDelegate *delegate = (ArtdepotAppDelegate*)[[UIApplication sharedApplication] delegate];
//	[delegate buyWorkFailed:transaction.payment.productIdentifier];	
}

- (void) restoreTransaction: (SKPaymentTransaction *)transaction {
    NSLog(@"restore id:%@", transaction.payment.productIdentifier);
    /*UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"恢复成功" 
                                                    message:@"你可以在此App中阅读完整版本，谢谢你的使用。\n\n你也可以下载书店模式的App“长江阅读”，里面包含丰富的图书资源，并有大量的免费图书供选择。" 
                                                   delegate:self 
                                          cancelButtonTitle:@"好" 
                                          otherButtonTitles:nil, nil];
    [alert show];
    [alert release];
    */
    DBUtil *db = [[DBUtil alloc] init];
    [db openDB];
    [db updateBook:@"appleid" key:[transaction.payment.productIdentifier stringByReplacingOccurrencesOfString:@".a02." withString:@".a01."] value:@"1"];
    [db closeDB];
    [db release];
    
    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}

-(void) paymentQueueRestoreCompletedTransactionsFinished: (SKPaymentTransaction *)transaction{
	//NSLog(@"transaction finihed");
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"恢复操作完成提示" 
                                                    message:@"1) 如果你之前已经购买过图书，则所有之前付费购买的图书的价格按钮变成“下载”按钮，点击直接下载，无需在此付费；\n2）如果你之前从未购买，则恢复功能没有作用。" 
                                                   delegate:self 
                                          cancelButtonTitle:@"好" 
                                          otherButtonTitles:nil, nil];
    [alert show];
    [alert release];
    
	//[[SKPaymentQueue defaultQueue] finishTransaction: transaction];
    HubuAppDelegate *delegate = (HubuAppDelegate *)[[UIApplication sharedApplication] delegate];
	delegate.hubuViewController.isDownloading = FALSE;
}

-(void) paymentQueue:(SKPaymentQueue *) paymentQueue restoreCompletedTransactionsFailedWithError:(NSError *)error
{
	UIAlertView *alerView =  [[UIAlertView alloc] initWithTitle:@"警告" message:[error localizedDescription]
													   delegate:nil cancelButtonTitle:@"关闭" otherButtonTitles:nil];
	
	[alerView show];
	[alerView release];
    HubuAppDelegate *delegate = (HubuAppDelegate *)[[UIApplication sharedApplication] delegate];
	delegate.hubuViewController.isDownloading = FALSE;
}

@end
